# -*- coding: latin-1 -*-
from django import template

register = template.Library()
from datetime import *

import re


@register.simple_tag
def get_at(obj,atr):
	value = ""
	try:
		value = getattr(obj, atr)()
	except:
		try:
			value = getattr(obj, atr)
		except:
			value =""
	if isinstance(value,date):
		value = value.strftime("%d/%m/%Y")
	return value

@register.simple_tag
def repeat_text(text,times):
	value = ""
	for i in range(times-1):
		value += text
	return value
	
@register.simple_tag
def is_instance(obj,clase):
	return isinstance(obj,clase)

@register.simple_tag
def iterate_td(obj,selec):
	ret = ""
	for a in select:
		ret += " <td>%s</td> " % get_at(obj,a)
	return ret
	
def attr_concat(first,last):
	return "%s.%s" %(first,last)	

def get_attr_con(obj,first,last):
	ret = "%s.%s" %(first,last)
	return get_at(obj,ret)



def show_row(row,titles):
	""" imprime los campos de la fila row, con el color correspondiente de colors
	 el nivel es el primer campo de row """
	ret = ""
	title = row[0]=="Title"
	total = re.match(r'total-(?P<nivel>\d+)',str(row[0]))
	for i in range(len(row)):
		if i == 0:
			if title:
				ret = "<thead class='fixedHeader'><tr class=titulo>"
			elif total:
				ret = "<tr class=%s  >" % row[i]
			else:
				ret = "<tr class=nivel-%s >" % row[i]
		else:
			t = ""
			if i == 1:
				if not title:
					if total:
						t = repeat_text("&nbsp;", int(total.group("nivel"))*10)
						t += "Total:"
					else:
						t = repeat_text("&nbsp;", int(row[0])*10)
					
			if row[i]:
				if row[i] == 'True':
					row[i] = titles[i]
				t += u"%s" % row[i]
			else:
				t += "&nbsp;"
			if title:
				ret += "<th > <a href=#>%s</a></th>"%t
			else:
				ret += "<td width=200>%s</td>"%t
			
		
	ret += "</tr>"
	if title:
		ret += "</thead>"
	return ret		

@register.simple_tag	
def show_table(table):
	""" imprime las filas de table, la primera son los titulos """
	ret = ""
	titles = table[0]
	le = len(table)
	for i,row in enumerate(table):
		if i == 1:
			ret += "<tbody class='scrollContent'>"
		ret += show_row (row,titles) 
		if i == le-1:
			ret += "</tbody>"
	return ret		

@register.simple_tag	
def rows(table):
	return len(table) - 1
